package com.cms.html;


import com.cms.common.model.entity.AdminUser;
import com.cms.common.model.vo.Menu;
import com.cms.component.menu.MenuConfig;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.templateresolver.FileTemplateResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TemplateEngineService {
    public static Map<String, SpringTemplateEngine> templateEngines = new HashMap<>();
    public static Map<String, String> templatesPath = new HashMap<>();

    public static SpringTemplateEngine getTemplateResolver(String prefix) {

        if (templateEngines.containsKey(prefix)) {
            //return templateEngines.get(prefix);
        }
        FileTemplateResolver resolver = new FileTemplateResolver();
        resolver.setPrefix(templatesPath.get(prefix));
        resolver.setSuffix(".html");
        resolver.setTemplateMode("HTML5");
        SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();
        springTemplateEngine.setTemplateResolver(resolver);
        templateEngines.put(prefix, springTemplateEngine);
        return springTemplateEngine;
    }


    public static String layoutProcess(String html, Map<String, Object> variables, Context context) {
        String htmlRs = null;
        Document doc = Jsoup.parse(html);
        Elements mainLayoutEles = doc.select("cms-layout");
        if (!mainLayoutEles.isEmpty()) {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            AdminUser adminUser = (AdminUser) request.getAttribute("adminUser");
            variables.put("adminUser", adminUser);
            List<Menu> menus = MenuConfig.getMenus(adminUser,request);
            variables.put("menus", menus);

            for (Element element : mainLayoutEles) {
                if (element.hasAttr("layout")) {
                    String layoutPath = element.attr("layout");
                    String[] layouts = layoutPath.split("::");
                    String layoutProject = "";
                    String layout = "";
                    if (layouts.length == 1) {
                        String path = getTemplatePath();
                        layoutProject = getLayoutProject(path);
                        layout = "\\" + layouts[0];
                    } else {
                        layoutProject = layouts[0];
                        layout = "\\" + layouts[1];
                    }


                    String childHtml = "";
                    Elements elements = element.children();
                    for (Element child : elements) {
                        childHtml = childHtml + child.toString();
                    }

                    variables.put("layoutContent", childHtml);
                    context.setVariables(variables);
                    String layoutPage = getTemplateResolver(layoutProject).process(layout, context);
                    htmlRs = Jsoup.parse(layoutPage).toString();
                    break;
                }
            }

        }
        return htmlRs;
    }





    public static void initTemplatePath() {
        String path = getTemplatePath();
        if (path != null) {
            String layoutProject = getLayoutProject(path);
            if (!templatesPath.containsKey(layoutProject)) {
                templatesPath.put(layoutProject, path);
            }
        }
    }

    private static String getLayoutProject(String path) {
        String tmpPath = path.replace("/target/classes/templates", "");
        String[] tmpPaths = tmpPath.split("/");
        String layoutProject = tmpPaths[tmpPaths.length - 1];
        return layoutProject;
    }

    public static String getTemplatePath() {

        Resource resource = new ClassPathResource("templates");
        String path = null;
        try {
            path = resource.getURI().getPath();
            return path;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }
}